import axios from 'axios'
import {ElMessage, ElNotification} from "element-plus";

// 创建axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL, // api 的 base_url
    timeout: import.meta.env.VITE_API_REQUEST_TIME_OUT,// 请求超时时间
    withCredentials: true, // 跨域请求时发送 cookies
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'Access-Control-Allow-Origin': '*'
    }
})

// request 拦截器
service.interceptors.request.use(config => {
    // console.log("触发request拦截器")
    if (localStorage.getItem("token")!==null) {  //
        // 判断是否存在token，如果存在的话，则每个http header都加上token
        config.headers.token = localStorage.getItem("token")
        //console.log(config.headers.authorization)
    }
    return config
}, error => {
    return Promise.reject(error)
})

// response 拦截器
service.interceptors.response.use(
    response => {
        // console.log("触发response拦截器")
        const responseData = response.data
        if (responseData.code !== 1) {
            ElNotification({
                message: responseData.message,
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject('error')
        } else {
            return responseData
        }
    },
    error => {
        ElMessage({
            message: '服务器错误',
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
